<template>
	<div class="table-box">
		<ProTable
			ref="proTable"
			title="地址管理"
			:columns="columns"
			:requestApi="getTableList"
			:initParam="initParam"
			:dataCallback="dataCallback"
		>
			<!-- 表格 header 按钮 -->
			<template #tableHeader="scope">
				<el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增地址</el-button>
				<!-- <el-button type="primary" :icon="Upload" plain @click="batchAdd" v-auth="'batchAdd'">批量添加用户</el-button> -->
				<!-- <el-button type="primary" :icon="Download" plain @click="downloadFile" v-auth="'export'">导出用户数据</el-button> -->
				<!-- <el-button type="primary" plain @click="toDetail">To 子集详情页面</el-button> -->
				<el-button v-auth="'batchAdd'" type="danger" :icon="Delete" plain :disabled="!scope.isSelected"> 批量删除用户 </el-button>
				<el-button
					v-upload-file="{
						type: ['xls', 'xlsx'],
						size: 5,
						limit: 1
					}"
					@upload="readExcelFile"
					type="primary"
					:icon="UploadFilled"
					>批量导入</el-button
				>
				<el-button @click="downLoadModel" type="warning" :icon="Download">模版下载</el-button>
			</template>
			<!-- Expand -->
			<template #expand="scope">
				{{ scope.row }}
			</template>
			<!-- 表格操作 -->
			<template #operation="scope">
				<!-- <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)">查看</el-button> -->
				<el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)">编辑</el-button>
				<!-- <el-button type="primary" link :icon="Refresh" @click="resetPass(scope.row)">重置密码</el-button> -->
				<el-button type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">删除</el-button>
			</template>
		</ProTable>
		<UserDrawer ref="drawerRef" />
		<ImportExcel ref="dialogRef" />

		<el-dialog title="导入结果" v-model="dialogUpLoad" width="500px" :before-close="handleClose">
			<div style="padding: 20px">
				<el-progress :percentage="(((getNumBatchSucNum + getNumBatchErrNum) / selectList.length) * 100).toFixed()" />

				<div style="margin-top: 15px; font-size: 16px">
					共 {{ selectList.length }} 单，成功 {{ getNumBatchSucNum }} 单，失败 {{ getNumBatchErrNum }} 单
				</div>
			</div>
			<template #footer>
				<el-button type="primary" @click="dialogUpLoad = false">确 定</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup lang="tsx" name="address">
import { ref, reactive } from "vue";
// import { ElMessage, ElMessageBox } from "element-plus";
import {
	listClientAddress,
	updateClientAddress,
	createClientAddress,
	delClientAddress,
	importCustomerAddress
} from "@/api/modules/address";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "@/views/address/components/UserDrawer.vue";
import { CirclePlus, Delete, EditPen, UploadFilled, Download } from "@element-plus/icons-vue";

import XLSX from "xlsx-js-style";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { sheet2Data } from "@/utils/excel";
import { AddressCorrect } from "@/api/base/index";
import _ from "lodash";
const downLoadModel = () => {
	window.location.href =
		"https://syd-pub.oss-cn-qingdao.aliyuncs.com/download/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93/%E4%B8%80%E8%88%AC%E8%B4%B8%E6%98%93%E6%89%B9%E9%87%8F%E5%AF%BC%E5%85%A5%E5%AE%A2%E6%88%B7-%E5%89%8D%E5%8F%B0.xlsx";
};
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
const dialogUpLoad = ref(false);
const handleClose = () => {
	dialogUpLoad.value = false;
};
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
	return {
		list: data.data,
		total: data.total
		// pageNum: data.pageNum,
		// pageSize: data.pageSize
	};
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
	let newParams = JSON.parse(JSON.stringify(params));
	return listClientAddress(newParams);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const status = reactive([
	{
		userLabel: "是",
		userStatus: 1
	},
	{
		userLabel: "否",
		userStatus: 2
	}
]);
// 表格配置项
const columns: ColumnProps[] = [
	// { type: "selection", fixed: "left", width: 80 },
	{ type: "index", label: "#", width: 80 },
	// { type: "expand", label: "Expand", width: 100 },
	{
		prop: "client.username",
		label: "客户名称",
		search: { el: "input" },
		width: 150
	},
	{ prop: "nation", label: "国家", search: { el: "input" }, width: 80 },
	{
		prop: "name",
		label: "收件人",
		search: { el: "input" },
		width: 150
	},
	// 多级 prop
	{
		prop: "address",
		label: "电话",
		width: 150,
		render: (scope: { row: any }) => {
			return (
				<>
					+{scope.row.area_code} {scope.row.mobile}
				</>
			);
		}
	},
	{
		prop: "detailed",
		label: "地址",
		minWidth: 300,
		render: (scope: { row: any }) => {
			return (
				<>
					{scope.row.nation} {scope.row.province} {scope.row.city} {scope.row.district} {scope.row.detailed}
				</>
			);
		}
	},
	{ prop: "postcode", label: "邮编", width: 100 },
	{
		prop: "is_default",
		label: "是否默认",
		enum: status,
		width: 100,
		search: { el: "tree-select", props: { filterable: true } },
		fieldNames: { label: "userLabel", value: "userStatus" },
		render: (scope: { row: any }) => {
			return (
				<>
					<el-tag type={scope.row.is_default == 1 ? "success" : "danger"}>{scope.row.is_default == 1 ? "是" : "否"}</el-tag>
				</>
			);
		}
	},
	{
		prop: "add_time",
		label: "创建时间",
		width: 180,
		search: {
			el: "date-picker",
			span: 1,
			props: {
				type: "datetimerange",
				valueFormat: "YYYY-MM-DD HH:mm:ss",
				defaultTime: [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]
			}
		}
	},
	{ prop: "operation", label: "操作", fixed: "right", width: 200 }
];

// 删除用户信息
const deleteAccount = async (params: any) => {
	await useHandleData(delClientAddress, { id: params.id }, `删除【${params.name}】的地址`);
	proTable.value.getTableList();
};
// 打开 drawer(新增、查看、编辑)
const drawerRef = ref();
const openDrawer = (title: string, rowData: any = {}) => {
	let params = {
		title,
		rowData: { ...rowData },
		isView: title === "查看",
		api: title === "新增" ? createClientAddress : title === "编辑" ? updateClientAddress : "",
		getTableList: proTable.value.getTableList
	};
	drawerRef.value.acceptParams(params);
};

const selectList: any = ref([]);
const getNumBatchSucNum = ref(0);
const getNumBatchErrNum = ref(0);
const upFile = (list: any) => {
	return new Promise((resolve, reject) => {
		importCustomerAddress({
			list: list
		}).then((res: any) => {
			getNumBatchErrNum.value += res.data.length;
			getNumBatchSucNum.value += list.length - res.data.length;
			resolve(true);
		});
	});
};
/**
 * 根据sheet索引读取Excel文件中的数据
 /**@param file 文件
 /** @param sheetIndex excel文件中sheet表索引 默认是从0开始
 /**@returns  将表中的数据以json形式的数据返回
*/
const readExcelFile = async (e: any) => {
	const loading = ElLoading.service({
		lock: true,
		text: "Loading",
		background: "rgba(0, 0, 0, 0.7)"
	});
	let data = await readFile(e);
	let workbook = XLSX.read(data);
	let worksheet = workbook.Sheets[workbook.SheetNames[0]];
	// data = XLSX.utils.sheet_to_json(worksheet);
	let file = sheet2Data(worksheet, "I");
	// let arr = [
	// 	"用户名",
	// 	"客户名称",
	// 	"客户唛头",
	// 	"客户代码",
	// 	"姓名",
	// 	"电话区号\n中国86\n韩国82\n日本81",
	// 	"手机号",
	// 	"邮编",
	// 	"详细地址"
	// ];
	// if (!_.isEqual(arr, file[2])) {
	// 	ElMessage.error("上传模版错误");
	// 	loading.close();
	// 	return false;
	// }
	let goodList = file.splice(3, file.length - 1);
	selectList.value = [];
	getNumBatchSucNum.value = 0;
	getNumBatchErrNum.value = 0;

	for (let index in goodList) {
		let item: any = goodList[index];
		let address: any = await addressCorrect(item[8]);
		let obj: any = {
			username: item[0],
			client_username: item[1],
			user_mark: item[2],
			code: item[3],
			name: item[4],
			area_code: item[5],
			mobile: item[6],
			postcode: item[7],
			nation: "中国",
			province: address.province,
			city: address.city,
			district: address.district,
			detailed: address.detailed
		};
		selectList.value.push(obj);
	}
	const chunkList = _.chunk(selectList.value, 10);
	loading.close();
	dialogUpLoad.value = true;
	for (let index = 0; index < chunkList.length; index++) {
		const element = chunkList[index];
		await upFile(element);
	}
	proTable.value.getTableList();
};
/**
 * 把文件按照二进制进行读取
 * @param file
 * @returns
 */
const readFile = (file: File) => {
	return new Promise(resolve => {
		let reader = new FileReader();
		reader.readAsArrayBuffer(file);
		reader.onload = ev => {
			resolve(ev.target?.result);
		};
	});
};
const addressCorrect = (address: any) => {
	return new Promise((resolve, reject) => {
		if (address) {
			AddressCorrect({
				country: "CN",
				address: address
			}).then((res: any) => {
				resolve({
					province: res.data.state,
					city: res.data.city,
					district: res.data.district,
					detailed: res.data.detail
				});
			});
		} else {
			resolve({
				province: "",
				city: "",
				district: "",
				detailed: ""
			});
		}
	});
};
</script>
